﻿using markdown_picture_packer.common.enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace markdown_picture_packer.backend
{
    public class Picture
    {
        // 上下文索引
        public readonly int Index;
        // 正则匹配的字符串   只有这两种 一种 是 ![]()  另一种是 <img>
        // RegexContent = ![InfoRange包含范围的内容](UrlRange包含范围的内容)
        // RegexContent = <img src="UrlRange的内容">
        public readonly string MatchedStr;
        // 信息范围  <img>格式里没有InfoRange
        public readonly Range InfoRange;
        // 路径范围
        public readonly Range UrlRange;
        // 资源路径
        public readonly string SrcPath;
        // 图片类型
        public readonly PictureType Type;
        // 显示类型
        public readonly PictureShowType ShowType;
        public Picture(int index, string mdFolderPath, string matchedStr, string info, string url, PictureShowType showType) : this(index, mdFolderPath, matchedStr, info, url, showType, 0) { }

        public Picture(int index, string mdFolderPath, string matchedStr, string info, string url, PictureShowType showType, int startIndex)
        {
            Index = index;
            MatchedStr = matchedStr;
            ShowType = showType;
            bool isMarkdown = ShowType == PictureShowType.MARKDOWN;
            InfoRange = isMarkdown ? GetReplaceRange(MatchedStr, info, startIndex) : null;
            UrlRange = isMarkdown ? GetReplaceRange(MatchedStr, url, InfoRange.End) : GetReplaceRange(MatchedStr, url, startIndex);
            bool isNet = url.Trim().StartsWith("http");
            Type = isNet ? PictureType.NET : PictureType.LOCAL;
            SrcPath = isNet ? url : File.Exists(url) ? url : Path.Combine(mdFolderPath, url);
        }
        //获取子字符串串在父字符串的Range
        public Range GetReplaceRange(string parentStr, string childStr, int startIndex)
        {
            int begin = parentStr.IndexOf(childStr, startIndex);
            return new Range(begin, begin + childStr.Length);
        }
        // 获取替换后的字符串
        public string GetReplaceAfterStr(string info, string content)
        {
            if (ShowType == PictureShowType.HTML_TAG)
                return MatchedStr.Substring(0, UrlRange.Start) + content + MatchedStr.Substring(UrlRange.End);
            else
                return MatchedStr.Substring(0, InfoRange.Start) + info + MatchedStr.Substring(InfoRange.End, UrlRange.Start - InfoRange.End) +
                    content + MatchedStr.Substring(UrlRange.End);
        }
    }
}
